/**
 * Sensor Network Development Kit for 1-Wire Network (SeN)
 * Version : 0.1
 * Revision date : 2008-10-13
 * Author: Dubravko Penezic, dpenezic@gmail.com
 * 
 * Based on T. Bitson, SimpleWeather, OWHub.java, 2007
 */

package owLib;

import com.dalsemi.onewire.*;
import com.dalsemi.onewire.adapter.*;
import com.dalsemi.onewire.container.*;

/**
 * OWHub class manage hub/switch on 1-Wire network
 * Version : 0.1.1
 * Revision date : 2008-10-13
 * 
 * @author Dubravko Penezic, dpenezic@gmail.com
 *
 */

public class OWHub
{
  // class variables
  private DSPortAdapter adapter;
  private OneWireContainer1F owSwitch;
  
  private OWConf c; 

/**
 * OWHub method set parameters and init hub/switch on 1-Wire network
 *   
 * @param adapter
 * @param owDeviceAddress
 */
  public OWHub(DSPortAdapter adapter, String owDeviceAddress)
  {
    	
    if (c.debugFlag)
      System.out.println("Initializing the Hub...");
      
      if (c.debugFlag)
          System.out.println("init Adapter: " + adapter.getAdapterName() + " device " + owDeviceAddress);
    
      owSwitch = new OneWireContainer1F(adapter, owDeviceAddress);
  }
  
  /**
   * deactivateAllPorts method deactivate all ports on hub/switch 
   *  
   */  
  public void deactivateAllPorts()
  {
    
      deactivatePort("main");
      deactivatePort("aux");
    
  }
  
  /**
   * activatePort method activate port on hub/switch 
   *  
   * @param port "main" or "aux"
   */  
  public void activatePort(String port)
  {
    int ch;
    
    if (c.debugFlag)
      System.out.println("Hub: Activating channel port " + port);
       
    if (port.toLowerCase().equals("main"))
      ch = 0;
    else if (port.toLowerCase().equals("aux"))
      ch = 1;
    else
    {
      System.out.println("activate() Error - Invalid Hub aux/main command: " + port);
      return;
    }
    
    try
    {
      byte[] state = owSwitch.readDevice();
      owSwitch.setLatchState(ch, true, false, state);
      owSwitch.writeDevice(state);
    }
    catch (OneWireException e)
    {
      System.out.println("Error Setting Hub: " + e);
    }
  }
  
/**
 * deactivatePort method deactivate port on hub/switch 
 *  
 * @param port "main" or "aux"
 */
  public void deactivatePort(String port)
  {
    int ch;

    if (c.debugFlag)
      System.out.println("Hub: dectivating port " + port);
    
    if (port.toLowerCase().equals("main"))
      ch = 0;
    else if (port.toLowerCase().equals("aux"))
      ch = 1;
    else
    {
      System.out.println("deactivate() Error -  - Invalid Hub aux/main command");
      return;
    }  
    
    try
    {
      byte[] state = owSwitch.readDevice();
      owSwitch.setLatchState(ch, false, false, state);
      owSwitch.writeDevice(state);
    }
    catch (OneWireException e)
    {
      System.out.println("Error Setting Hub: " + e);
    }  

  }
  
}
